package org.alis.rpc.route.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.alis.rpc.common.protocol.RpcProtocol;
import org.alis.rpc.handler.RpcClientHandler;
import org.alis.rpc.route.AbstractRpcLoadBalance;

import java.util.*;

/**
 * RpcLoadBalanceLFU desc: 最不经常使用
 *
 * @author luochuan
 * @date 2020/10/9 14:17
 */
public class RpcLoadBalanceLFU<V> extends AbstractRpcLoadBalance<V> {

    private Map<String, Map<RpcProtocol, Integer>> jobLfuMap = Maps.newConcurrentMap();
    private static long CACHE_VALID_TIME = 0;

    @Override
    public RpcProtocol doRoute(String serviceKey, List<RpcProtocol> addressList) {
        // cache clear
        if (System.currentTimeMillis() > CACHE_VALID_TIME) {
            jobLfuMap.clear();
            CACHE_VALID_TIME = System.currentTimeMillis() + 1000 * 60 * 60 * 24;
        }

        // lfu item init
        Map<RpcProtocol, Integer> lfuItemMap = jobLfuMap.get(serviceKey);
        if (lfuItemMap == null) {
            lfuItemMap = Maps.newHashMap();
            // 避免重复覆盖
            jobLfuMap.putIfAbsent(serviceKey, lfuItemMap);
        }

        // put new
        for (RpcProtocol address : addressList) {
            if (!lfuItemMap.containsKey(address) || lfuItemMap.get(address) > 1000000) {
                lfuItemMap.put(address, 0);
            }
        }

        // remove old
        List<RpcProtocol> delKeys = new ArrayList<>();
        for (RpcProtocol existKey : lfuItemMap.keySet()) {
            if (!addressList.contains(existKey)) {
                delKeys.add(existKey);
            }
        }
        if (delKeys.size() > 0) {
            for (RpcProtocol delKey : delKeys) {
                lfuItemMap.remove(delKey);
            }
        }

        // load least used count address
        List<Map.Entry<RpcProtocol, Integer>> lfuItemList = Lists.newArrayList(lfuItemMap.entrySet());
        lfuItemList.sort(Comparator.comparing(Map.Entry::getValue));

        Map.Entry<RpcProtocol, Integer> addressItem = lfuItemList.get(0);
        RpcProtocol minAddress = addressItem.getKey();
        addressItem.setValue(addressItem.getValue() + 1);

        return minAddress;
    }


}
